// 全局变量
let socket = null;
let charts = {};
let simulationData = [];
let isPaused = false;
let playSpeed = 1.0;
let currentStep = 0;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeSocket();
    initializeCharts();
    bindEvents();
});

// Socket.IO 初始化
function initializeSocket() {
    socket = io();
    
    socket.on('connect', function() {
        console.log('Connected to server');
        updateStatus('已连接到服务器');
    });
    
    socket.on('simulation_data', function(data) {
        handleSimulationData(data);
    });
    
    socket.on('simulation_complete', function() {
        updateStatus('模拟完成');
        document.getElementById('startBtn').disabled = false;
        document.getElementById('pauseBtn').disabled = true;
    });
    
    socket.on('disconnect', function() {
        console.log('Disconnected from server');
        updateStatus('连接已断开');
    });
}

// 初始化图表
function initializeCharts() {
    // 水深分布图
    const depthCtx = document.getElementById('depthChart').getContext('2d');
    charts.depth = new Chart(depthCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '水深 (m)',
                data: [],
                borderColor: 'rgb(0, 123, 255)',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: {
                    title: {
                        display: true,
                        text: '巷道位置 (m)'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: '水深 (m)'
                    },
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    display: true
                }
            }
        }
    });
    
    // 流速分布图
    const velocityCtx = document.getElementById('velocityChart').getContext('2d');
    charts.velocity = new Chart(velocityCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '流速 (m/s)',
                data: [],
                borderColor: 'rgb(220, 53, 69)',
                backgroundColor: 'rgba(220, 53, 69, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: {
                    title: {
                        display: true,
                        text: '巷道位置 (m)'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: '流速 (m/s)'
                    },
                    beginAtZero: true
                }
            }
        }
    });
    
    // 突水流量变化图
    const flowCtx = document.getElementById('flowChart').getContext('2d');
    charts.flow = new Chart(flowCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '突水流量 (m³/s)',
                data: [],
                borderColor: 'rgb(40, 167, 69)',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: {
                    title: {
                        display: true,
                        text: '时间 (s)'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: '流量 (m³/s)'
                    },
                    beginAtZero: true
                }
            }
        }
    });
}

// 绑定事件
function bindEvents() {
    // 开始模拟
    document.getElementById('startBtn').addEventListener('click', startSimulation);
    
    // 暂停/继续
    document.getElementById('pauseBtn').addEventListener('click', togglePause);
    
    // 重置
    document.getElementById('resetBtn').addEventListener('click', resetSimulation);
    
    // 播放速度
    document.getElementById('speedSlider').addEventListener('input', function(e) {
        playSpeed = parseFloat(e.target.value);
        document.getElementById('speedValue').textContent = playSpeed.toFixed(1) + 'x';
    });
    
    // 导出数据
    document.getElementById('exportBtn').addEventListener('click', exportData);
    
    // 截图保存
    document.getElementById('screenshotBtn').addEventListener('click', takeScreenshot);
}

// 开始模拟
function startSimulation() {
    const params = {
        L: parseFloat(document.getElementById('L').value),
        B: parseFloat(document.getElementById('B').value),
        n: parseFloat(document.getElementById('n').value),
        S0: parseFloat(document.getElementById('S0').value),
        Q_inject: parseFloat(document.getElementById('Q_inject').value),
        t_peak: parseFloat(document.getElementById('t_peak').value),
        t_total: parseFloat(document.getElementById('t_total').value),
        x_inject: parseFloat(document.getElementById('x_inject').value)
    };
    
    fetch('/api/start', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(params)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'started') {
            updateStatus('模拟进行中...');
            document.getElementById('startBtn').disabled = true;
            document.getElementById('pauseBtn').disabled = false;
            simulationData = [];
            currentStep = 0;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        updateStatus('启动失败: ' + error.message);
    });
}

// 暂停/继续
function togglePause() {
    isPaused = !isPaused;
    const btn = document.getElementById('pauseBtn');
    if (isPaused) {
        btn.innerHTML = '<i class="fas fa-play"></i> 继续';
        updateStatus('模拟已暂停');
    } else {
        btn.innerHTML = '<i class="fas fa-pause"></i> 暂停';
        updateStatus('模拟进行中...');
    }
}

// 重置模拟
function resetSimulation() {
    fetch('/api/reset', {
        method: 'POST'
    })
    .then(() => {
        simulationData = [];
        currentStep = 0;
        isPaused = false;
        
        // 重置图表
        Object.values(charts).forEach(chart => {
            chart.data.labels = [];
            chart.data.datasets[0].data = [];
            chart.update();
        });
        
        document.getElementById('startBtn').disabled = false;
        document.getElementById('pauseBtn').disabled = true;
        document.getElementById('pauseBtn').innerHTML = '<i class="fas fa-pause"></i> 暂停';
        
        updateStatus('已重置，等待开始模拟...');
        document.getElementById('currentTime').textContent = '0.0';
    });
}

// 处理模拟数据
function handleSimulationData(data) {
    if (isPaused) return;
    
    simulationData.push(data);
    
    // 更新图表
    updateCharts(data);
    
    // 更新时间显示
    document.getElementById('currentTime').textContent = data.time.toFixed(1);
}

// 更新图表
function updateCharts(data) {
    // 水深分布图
    charts.depth.data.labels = data.x.map(x => x.toFixed(0));
    charts.depth.data.datasets[0].data = data.h;
    charts.depth.update();
    
    // 流速分布图
    charts.velocity.data.labels = data.x.map(x => x.toFixed(0));
    charts.velocity.data.datasets[0].data = data.v;
    charts.velocity.update();
    
    // 突水流量图 - 累积显示
    if (charts.flow.data.labels.length > 50) {
        charts.flow.data.labels.shift();
        charts.flow.data.datasets[0].data.shift();
    }
    charts.flow.data.labels.push(data.time.toFixed(1));
    charts.flow.data.datasets[0].data.push(data.Q);
    charts.flow.update();
}

// 导出数据
function exportData() {
    if (simulationData.length === 0) {
        alert('没有可导出的数据，请先运行模拟');
        return;
    }
    
    const csvContent = "data:text/csv;charset=utf-8," 
        + "时间(s),位置(m),水深(m),流速(m/s),流量(m³/s)\n"
        + simulationData.flatMap(data => 
            data.x.map((x, i) => 
                `${data.time},${x},${data.h[i]},${data.v[i]},${data.Q}`
            )
        ).join("\n");
    
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `flood_simulation_${Date.now()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 截图保存
function takeScreenshot() {
    const chartsContainer = document.querySelector('.col-md-9');
    
    // 使用html2canvas库（需要额外引入）
    if (typeof html2canvas !== 'undefined') {
        html2canvas(chartsContainer).then(canvas => {
            const link = document.createElement('a');
            link.download = `flood_screenshot_${Date.now()}.png`;
            link.href = canvas.toDataURL();
            link.click();
        });
    } else {
        // 简单的替代方案：下载当前图表数据
        alert('截图功能需要引入html2canvas库。当前可使用导出数据功能保存结果。');
    }
}

// 更新状态文本
function updateStatus(text) {
    document.getElementById('statusText').textContent = text;
}

// 格式化数字
function formatNumber(num, decimals = 2) {
    return parseFloat(num).toFixed(decimals);
}
